package org.example.uploadfile.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.result.Result;
import org.example.uploadfile.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController {

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) throws IOException {
        log.info("文件上传····················");
        // 获取文件原始名称
        String originalFilename = file.getOriginalFilename();

        // 使用UUID进行文件重命名
//        String timeName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 上传文件,传入文件名和文件流
        String url = AliOssUtil.uploadFile(fileName, file.getInputStream());
        log.info("文件上传成功············url:{}", url);
        return Result.success(url);
    }
}